package com.chezhujie.www.controller;

import com.chezhujie.www.domain.XyMenu;
import com.chezhujie.www.domain.Xyuser;
import com.chezhujie.www.service.HomeService;
import com.chezhujie.www.service.XyMenuService;
import com.chezhujie.www.service.XyuserService;
import com.chezhujie.www.web.RequestUtils;
import com.google.code.kaptcha.Constants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * Created by 汤伟杰 on 2017/5/14.
 */
@Controller
@RequestMapping("/admin")
public class HomeController2 {
    private static Logger logger = LoggerFactory.getLogger(HomeController2.class);

    @Autowired
    private HomeService homeService;
    @Autowired
    private XyuserService xyuserService;
    @Autowired
    private XyMenuService xyMenuService;


    @RequestMapping({"/index.do",""})
    public String home(HttpServletRequest req, HttpServletResponse resp,
                        ModelMap model) throws IOException {

        Xyuser xyuser = (Xyuser)req.getSession().getAttribute("user");
        if(xyuser==null){
            return "redirect:login.do";
        }
        //获取菜单栏
        //根据用户获取菜单栏权限
        //listmap : {title:'',list:{title:'',url:''}}
      /*  List<XyMenu> xyMenuList = null;
        if("admin".equals(xyuser.getUsername())){
            xyMenuList = xyMenuService.queryByAll();
        }else{
            xyMenuList = xyMenuService.queryByUserId(xyuser.getUserId());
        }
        List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
        Map<String, List<Map<String, Object>>> mapParentObj = new HashMap<String, List<Map<String, Object>>>();

        for (XyMenu menu : xyMenuList) {
            if(!"0".equals(menu.getParentId())){
                List<Map<String, Object>> list = mapParentObj.get(menu.getParentId());
                if(list==null){
                    list = new ArrayList<Map<String, Object>>();
                }
                if (menu.getStatus()!=null&&menu.getStatus()==1) {//菜单为显示状态才会显示
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("title", menu.getName());
                    map.put("url", menu.getUrl());
                    list.add(map);
                    mapParentObj.put(menu.getParentId(), list);
                }
            }
//            mapParentObj.put(menu.getParentId(), menu);
        }
        for (XyMenu xyMenu : xyMenuList) {
            if(xyMenu.getParentId()!=null&&"0".equals(xyMenu.getParentId())&&xyMenu.getStatus()!=null&&xyMenu.getStatus()==1){
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("title",xyMenu.getName());
                map.put("list",mapParentObj.get(xyMenu.getMenuId())==null?new ArrayList<Map>():mapParentObj.get(xyMenu.getMenuId()));
                listmap.add(map);
            }

        }
        Map<String, Object> map = new HashMap<String, Object>();
        model.addAttribute("listmap",listmap);*/
        return "admin/home";
    }

    /**
     * 用户登录页面
     * @param req
     * @param resp
     * @param model
     * @throws IOException
     */
    @RequestMapping(value = "/login.do",method = RequestMethod.GET)
    public String login(HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model) throws IOException {
     /*   StringBuffer sb = new StringBuffer();
        sb.append("<!DOCTYPE html>\n");
        sb.append("<html lang=\"en\">\n");
        sb.append("<head>\n");
        sb.append("<meta charset=\"UTF-8\">\n");
        sb.append("<title>Title</title>\n" );
        sb.append("</head>\n");
        sb.append("<body bgcolor=\"#FFFFFF\" text=\"#000000\">\n");
        sb.append("<script language='javascript'>top.location.href = '");
        sb.append(req.getContextPath()+"/admin/index.do");
        sb.append("'</script>\n");
        sb.append("</body>\n");
        sb.append("</html>");

        resp.getWriter().print(sb.toString());*/
        Integer loginCount = (Integer)req.getSession().getAttribute("loginCount");//得到登录次数
        if(loginCount!=null){
            if(loginCount>3){
                model.addAttribute("viewVcode", "viewVcode");
            }
        }

        return "admin/login";
    }

    /**
     * 登录验证
     * @param username
     * @param password
     * @param vcode
     * @param req
     * @param resp
     * @param model
     * @return
     */
    @RequestMapping(value = "login.do",method = RequestMethod.POST)
    public String login(String username,
                        String password,
                        String vcode,
                        HttpServletRequest req, HttpServletResponse resp,
                        ModelMap model) {



        Subject currentUser = SecurityUtils.getSubject();
        //3次重复登录失败，则会出现验证码
        Integer loginCount = (Integer)req.getSession().getAttribute("loginCount");//得到登录次数
        if(loginCount==null){
            loginCount = 0;
        }else{
            loginCount++;
            if(loginCount>3){
                model.addAttribute("viewVcode", "viewVcode");
                String goolgleVcode = (String)req.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);

                if(vcode==null){
                    model.addAttribute("msg", "验证码输入不能为空!");
                    return "admin/login";//验证失败
                }
                if(goolgleVcode!=null&&vcode!=null) {
                    if (goolgleVcode.toUpperCase().equals(vcode.toUpperCase())) {
//                        System.out.println("验证码校验成功");
                    } else {
                        model.addAttribute("msg", "验证码输入有误!");
                        return "admin/login";//验证失败
                    }
                }
            }
        }
        req.getSession().setAttribute("loginCount",loginCount);


        model.addAttribute("info",currentUser.isAuthenticated());//单用户登录
//            if (!currentUser.isAuthenticated()){//使用shiro来验证
                UsernamePasswordToken token = new UsernamePasswordToken(username, password);
                token.setRememberMe(true);//记住密码
                try {

                    currentUser.login(token);

                    Xyuser xyuser = xyuserService.getByUsername(token.getUsername());
                    xyuser.setLastLogin(new Date());
                    xyuser.setIp(RequestUtils.getIpAddr(req));
                    xyuserService.update(xyuser);
                    req.getSession().removeAttribute("loginCount");
                    return "redirect:loginTo.do";//验证成功
                } catch (IncorrectCredentialsException ice) {
                    model.addAttribute("msg", "用户名或密码不匹配!");
                } catch (LockedAccountException lae) {
                    model.addAttribute("msg", "账户已被冻结！");
                } catch (AuthenticationException ae) {
                    model.addAttribute("msg", "用户："+username+"\t身份验证失败！");
                }catch (Exception e){
                    e.printStackTrace();
                    logger.error("#error:",e);
                }
//            }
//        model.addAttribute("msg", "用户已登录，已下线当前用户");
//        currentUser.logout();
            return "admin/login";//验证失败

    }
    @RequestMapping(value = "loginTo.do")
    public String loginTo(HttpServletRequest req, HttpServletResponse resp,
                         ModelMap model) {

        return "admin/loginTo";
    }
    /**
     * 退出登录
     * @param req
     * @param resp
     * @param model
     * @return
     */
    @RequestMapping(value = "logout.do")
    public String logout(HttpServletRequest req, HttpServletResponse resp,
                         ModelMap model) {
        HttpSession session = req.getSession();
        session.removeAttribute("user");
        model.addAttribute("msg","退出登陆");
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return "redirect:index.do";
    }
    /** api测试页面 */
    @RequestMapping("/apiTest.do")
    public String apiTest(HttpServletRequest req, HttpServletResponse resp,
                      ModelMap model) throws Exception {
        return "admin/apiTest";

    }
    @RequestMapping(value = "unauth.do",method = RequestMethod.GET)
    public String unauthorizedUrl(
                        HttpServletRequest req, HttpServletResponse resp,
                        ModelMap model) {
        return "admin/unauth";
    }

    /**
     * 权限不足跳转页面
     * @param req
     * @param resp
     * @param model
     * @return
     */
    @RequestMapping(value = "nopermissions.do")
    public String nopermissions(
                        HttpServletRequest req, HttpServletResponse resp,
                        ModelMap model) {
//        String retUrl = req.getHeader("Referer");

//        model.addAttribute("returnUrl",retUrl);
        return "admin/nopermissions";
    }

    @RequestMapping("/left.html")
    public String left(HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model) throws IOException {
        Xyuser xyuser = (Xyuser)req.getSession().getAttribute("user");
        if(xyuser==null){
            return "redirect:login.do";
        }
        //获取菜单栏
        //根据用户获取菜单栏权限
        //listmap : {title:'',list:{title:'',url:''}}
        List<XyMenu> xyMenuList = null;
        if("admin".equals(xyuser.getUsername())){
            xyMenuList = xyMenuService.queryByAll();
        }else{
            xyMenuList = xyMenuService.queryByUserId(xyuser.getUserId());
        }
        List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
        Map<String, List<Map<String, Object>>> mapParentObj = new HashMap<String, List<Map<String, Object>>>();

        for (XyMenu menu : xyMenuList) {
            if(!"0".equals(menu.getParentId())){
                List<Map<String, Object>> list = mapParentObj.get(menu.getParentId());
                if(list==null){
                    list = new ArrayList<Map<String, Object>>();
                }
                if (menu.getStatus()!=null&&menu.getStatus()==1) {//菜单为显示状态才会显示
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("title", menu.getName());
                    map.put("url", menu.getUrl());
                    list.add(map);
                    mapParentObj.put(menu.getParentId(), list);
                }
            }
//            mapParentObj.put(menu.getParentId(), menu);
        }
        for (XyMenu xyMenu : xyMenuList) {
            if(xyMenu.getParentId()!=null&&"0".equals(xyMenu.getParentId())&&xyMenu.getStatus()!=null&&xyMenu.getStatus()==1){
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("title",xyMenu.getName());
                map.put("list",mapParentObj.get(xyMenu.getMenuId())==null?new ArrayList<Map>():mapParentObj.get(xyMenu.getMenuId()));
                listmap.add(map);
            }

        }
        Map<String, Object> map = new HashMap<String, Object>();
        model.addAttribute("listmap",listmap);
        return "admin/left";
    }
}
